<template>
  <div>
    <el-button
      type="danger"
      @click="addDomain"
      :icon="Plus"
      style="float: left; margin-left: 10px; width: 100px; height: 40px"
      >新增</el-button
    >&emsp;
    <el-button
      :disabled="!buttonDisable"
      type="danger"
      :icon="Check"
      @click="submitForm"
      style="float: left; margin-left: 25px; width: 100px; height: 40px"
      >保存</el-button
    >&emsp;
    <el-button
      :disabled="!buttonDisable"
      type="danger"
      @click="delDomain"
      :icon="Back"
      style="float: left; margin-left: 25px; width: 100px; height: 40px"
      >撤销</el-button
    >&emsp;
    <el-button
      :disabled="!buttonDisable"
      type="danger"
      :icon="Delete"
      style="float: left; margin-left: 25px; width: 100px; height: 40px"
      >删除</el-button
    >
  </div>
  <br />
  &emsp;
  <div style="font-size: 22px">
    转种日期：<el-date-picker
      v-model="ProDates"
      type="date"
      placeholder="Pick a date"
      :default-value="new Date()"
      style="width: 200px"
    />
    单据号：<el-input v-model="proCodes" style="width: 200px" disabled>
    </el-input>
    &nbsp;&nbsp; &nbsp;&nbsp; 流水号：
    <el-input v-model="weather" style="width: 200px" disabled> </el-input>
  </div>

  <br /><br />
  <hr style="font-size: 20px" />
  <br />

  <div class="table-container" style="height: 400px; position: relative">
    <table style="border-collapse: collapse">
      <tr>
        <td>序号</td>
        <td>育成羊耳号</td>
        <td>当前栋舍</td>
        <td>当前栏位</td>
        <td>转入栋舍</td>
        <td>转入栏位</td>
        <td>性别</td>
        <!-- <td>转种日龄</td> -->
      </tr>
      <tr v-for="(ruleForm, index) in loge.healthArray">
        <td>
          {{ ruleForm.indexNumber }}
        </td>
        <td>
          <el-select
            style="width: 100px"
            v-model="ruleForm.sleepInforId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in eweData"
              :label="item.earNumber"
              :value="item.sleepInforId"
              @click="getearMsg(index)"
            />
          </el-select>
        </td>
        <td>
          <el-select
            style="width: 100px"
            v-model="ruleForm.CurrentBarn"
            placeholder="无数据"
            disabled
          >
            <el-option
              v-for="item in Recordcottage"
              :label="item.cottageName"
              :value="item.cottagesId"
            />
          </el-select>
        </td>
        <td>
          <el-select
            style="width: 100px"
            v-model="ruleForm.CurrentPen"
            placeholder="无数据"
            disabled
          >
            <el-option
              v-for="item in Fields"
              :label="item.fieIdName"
              :value="item.fieIdId"
            />
          </el-select>
        </td>
        <td>
          <el-select
            style="width: 100px"
            v-model="ruleForm.transferBarn"
            placeholder="请选择"
          >
            <el-option
              v-for="item in Recordcottage2"
              :label="item.cottageName"
              :value="item.cottagesId"
              @click="getFields2(ruleForm.transferBarn, index)"
            />
          </el-select>
        </td>
        <td>
          <el-select
            style="width: 100px"
            v-model="ruleForm.transferPen"
            placeholder="请选择"
          >
            <el-option
              v-for="item in Fields2[index]"
              :label="item.fieIdName"
              :value="item.fieIdId"
            />
          </el-select>
        </td>
        <td>
          <el-select
            style="width: 100px"
            v-model="ruleForm.gender"
            placeholder="请选择"
          >
            <el-option label="公" :value="1" />
            <el-option label="母" :value="2" />
          </el-select>
        </td>
        <!-- <td>
          <el-input
            v-model="ruleForm.ageDay"
            placeholder="请输入转种日龄"
          ></el-input>
        </td> -->
      </tr>
    </table>
  </div>
  <div style="bottom: 0; left: 0; width: 100%">
    <hr />
    <el-button
      link
      type="danger"
      :icon="Plus"
      style="float: left; margin-left: 10px"
      @click="addDomain"
      >增行</el-button
    >&emsp;
    <el-button
      link
      type="danger"
      :icon="Minus"
      style="float: left; margin-left: 10px"
      @click="delDomain"
      >删行</el-button
    >&emsp;
    <br />
    <hr />
    <span style="vertical-align: top; width: 5%">&emsp; 备注</span>&emsp;
    <el-input type="textarea" style="width: 85%" placeholder="请输入备注信息" />
  </div>
</template>

<script setup lang="ts">
import {
  Check,
  Delete,
  Edit,
  Message,
  Back,
  Plus,
  Setting,
  SuccessFilled,
  Minus,
  Close,
} from '@element-plus/icons-vue';
import { reactive, ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useCounterStore } from '@/stores/counter';

const counterStore = useCounterStore();
const route = useRoute();
const router = useRouter();
//获取雪花id(单据号、流水号)
//单号
const proCodes = ref('');
const getIds1 = () => {
  axios
    .post('http://localhost:5039/api/ProductionManagement/GetId', {})
    .then((res) => {
      proCodes.value = res.data;
      //第一条单据号（需要单独赋值）
      loge.healthArray[0].descendantsCode = JSON.stringify(res.data);
      //console.log(loge.healthArray)
    });
};

//流水号
const weather = ref('');

const getIds2 = () => {
  axios
    .post('http://localhost:5039/api/ProductionManagement/GetId', {})
    .then((res) => {
      weather.value = res.data;
    });
};

//转种日期
const ProDates = new Date();

//序号
const numbers = ref(1);
const loge = reactive({
  healthArray: <any>[
    reactive({
      indexNumber: numbers.value,
      sleepInforId: '',
      //culledId: '',
      //measures: '',
      descendantsCode: '',
      descendantsLiu: '',
      descendantsDate: ProDates,
      //exitName: '',
    }),
  ],
});

//按钮禁用条件
const buttonDisable = computed(() => {
  return loge.healthArray.length > 0;
});
//增行
const addDomain = () => {
  loge.healthArray.push(
    reactive({
      indexNumber: loge.healthArray.length + numbers.value,
      descendantsCode: JSON.stringify(proCodes.value),
      descendantsLiu: JSON.stringify(weather.value),
      sleepInforId: '',
      descendantsDate: ProDates,
    })
  );
  console.log(loge.healthArray);
};

//减行
const delDomain = () => {
  loge.healthArray.splice(loge.healthArray.length - 1, 1);
};

//获取栋舍
const Recordcottage = ref<any>([]);
const Recordcottage2 = ref<any>([]);
const getRecordcottage = () => {
  axios
    .post('http://localhost:5039/api/Cottages/CottageList', {})
    .then((res) => {
      Recordcottage.value = res.data.data;
      Recordcottage2.value = res.data.data;
    });
};
//获取栏位
const Fields = ref<any>([]);
const Fields2 = ref<any>([]);
const getFields = (id: number) => {
  console.log(id);
  axios
    .post('http://localhost:5039/api/Cottages/SearchFields', {
      cottagesId: id,
      pageIndex: 1,
      pageSize: 100000000,
    })
    .then((res) => {
      console.log(res.data.data);
      Fields.value = res.data.data;
    });
};
const getFields2 = (id: number, index: any) => {
  Fields2.value[index] = [];
  axios
    .post('http://localhost:5039/api/Cottages/SearchFields', {
      cottagesId: id,
      pageIndex: 1,
      pageSize: 100000000,
    })
    .then((res) => {
      Fields2.value[index] = res.data.data;
      loge.healthArray[index].transferPen = '';
      console.log(Fields2.value);
    });
};
//获取羊只信息
const updates = reactive({
  sleepInforId: '',
  gender: '',
  CurrentBarn: '',
  CurrentPen: '',
});

//通过耳号和状态获取妊娠 的信息
const getearMsg = (index: any) => {
  const selectedEweID = loge.healthArray[index].sleepInforId; // 获取选中的 EweID
  console.log(selectedEweID);
  axios
    .get('http://localhost:5039/api/ProductionManagement/EarMasList', {
      params: {
        SleepInforId: selectedEweID,
        BreedStatuId: 0,
      },
    })
    .then((res) => {
      console.log(res.data.item);
      updates.sleepInforId = res.data.item.sleepInforId;
      updates.gender = res.data.item.gender;
      updates.CurrentBarn = res.data.item.recordcottageId;
      updates.CurrentPen = res.data.item.fieIdId;
      handleUpdate(); //调用更新数据的方法
    });
};
// 例子：通过表单输入更新数据
const handleUpdate = () => {
  const sleepInforId = updates.sleepInforId; // 假设你从表单获取到的 EweID
  const gender = updates.gender; // 假设你从表单获取到的 gender
  const currentBarn = updates.CurrentBarn; // 假设你从表单获取到的 CurrentBarn
  const currentPen = updates.CurrentPen; // 假设你从表单获取到的 CurrentPen
  console.log(sleepInforId, gender, currentBarn, currentPen);
  updateFieldsByEweID(sleepInforId, gender, currentBarn, currentPen);
};
const updateFieldsByEweID = (
  sleepInforId: string,
  gender: string,
  currentBarn: string,
  currentPen: string
) => {
  // 遍历 healthArray 找到 EweID 对应的项并更新
  const healthItem = loge.healthArray.find(
    (item: any) => item.sleepInforId === sleepInforId
  );

  if (healthItem) {
    healthItem.CurrentBarn = currentBarn;
    getFields(healthItem.CurrentBarn);
    healthItem.CurrentPen = currentPen;
    healthItem.gender = gender;
  } else {
    console.log(`没有找到sleepInforId为 ${sleepInforId} 的数据`);
  }
};

//获取耳号
const eweData = ref<any>([]);
const geteweData = () => {
  axios
    .get('http://localhost:5039/api/SleepBegin/SelectEarFeMale')
    .then((res) => {
      eweData.value = res.data.data;
    });
};

const submitForm = () => {
  let obj = reactive({
    datas: loge.healthArray,
  });
  axios
    .post('http://localhost:5039/api/Descendantsafte/Handle', obj)
    .then((res) => {
      if (res.data.data > 0) {
        ElMessage({
          message: '添加成功',
          type: 'success',
        });
        router.push('/descendentListView');
      }
    });
};

onMounted(() => {
  getIds1();
  getIds2();
  getRecordcottage();
  geteweData();
});
</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 设置第一行的 td 顶部边框加粗并设置为红色 */
table tr:first-child td {
  border-top: 3px solid red;
  /* 设置顶部边框为3px宽度的红色 */
  padding: 10px;
  text-align: center;
}

/* 设置 td 的样式 */

table td {
  padding: 10px;
  border: 1px solid #ccc;
  text-align: center;
  font-size: 14px;
  height: 60px;
  width: 150px;
  white-space: nowrap; /* 防止内容换行 */
}

/* 可选：为 table 添加样式 */
table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

/*______________________________________________________*/

.table-container {
  max-width: 100%;
  overflow-x: auto; /* 启用水平滚动 */
  margin: 20px 0; /* 设置容器的外边距 */
}
:deep(.el-input__wrapper) {
  box-shadow: none;
  text-align: center;
}

:deep(.el-select__wrapper) {
  box-shadow: none;
}
::v-deep(.center-input .el-input__inner) {
  text-align: center;
}
</style>
